# robot_model_viewer.py
import os
from PyQt5.QtWidgets import QLabel, QVBoxLayout, QWidget
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt

class RobotModelViewer(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        
        # 创建标签用于显示图片
        self.image_label = QLabel()
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setStyleSheet("background-color: #1e1e1e; border: 1px dashed #0078d4;")
        self.layout.addWidget(self.image_label)
        
        # 设置默认提示文本
        self.set_default_message()
        
        # 初始化图片路径
        self.init_image_paths()
    
    def init_image_paths(self):
        """初始化图片路径"""
        # 获取项目根目录
        project_root = os.path.dirname(os.path.abspath(__file__))
        # 构建图片文件夹路径
        self.images_dir = os.path.join(project_root, "robot_images")
        
        # 如果文件夹不存在，创建它
        if not os.path.exists(self.images_dir):
            os.makedirs(self.images_dir)
            print(f"创建图片文件夹: {self.images_dir}")
        
        # 查找所有图片文件
        self.image_files = []
        if os.path.exists(self.images_dir):
            for filename in os.listdir(self.images_dir):
                if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp')):
                    self.image_files.append(filename)
        
        # 排序确保顺序一致
        self.image_files.sort()
        
        # 如果有图片，显示第一张
        if self.image_files:
            self.show_image(self.image_files[0])
    
    def show_image(self, filename):
        """显示指定图片"""
        try:
            # 构建完整的文件路径
            image_path = os.path.join(self.images_dir, filename)
            
            # 检查文件是否存在
            if not os.path.exists(image_path):
                print(f"图片文件不存在: {image_path}")
                return
            
            # 加载图片
            pixmap = QPixmap(image_path)
            
            # 如果图片太大，进行缩放
            if pixmap.width() > 600 or pixmap.height() > 400:
                pixmap = pixmap.scaled(600, 400, Qt.KeepAspectRatio, Qt.SmoothTransformation)
            
            # 显示图片
            self.image_label.setPixmap(pixmap)
            self.image_label.setText("")
            
        except Exception as e:
            print(f"显示图片时出错: {e}")
            self.set_default_message()
    
    def set_default_message(self):
        """设置默认提示消息"""
        self.image_label.setText("机器人模型展示区域\n(请添加机器人图片到robot_images文件夹)")
        self.image_label.setStyleSheet("background-color: #1e1e1e; border: 1px dashed #0078d4; color: #cccccc; font-size: 14px;")

    def next_image(self):
        """切换到下一张图片"""
        if not self.image_files:
            return
        
        # 获取当前显示的图片
        pixmap = self.image_label.pixmap()
        if pixmap is not None:
            # 如果当前有图片显示，则找到当前图片在列表中的位置
            current_pixmap = self.image_label.pixmap()
        else:
            current_pixmap = None
            
        if not self.image_label.text() and current_pixmap is not None:
            # 当前显示的是图片
            current_index = 0
        else:
            # 当前显示的是文本提示
            current_index = -1
            
        # 查找当前显示的图片文件名
        for i, filename in enumerate(self.image_files):
            image_path = os.path.join(self.images_dir, filename)
            current_pixmap_path = self.image_label.pixmap() if self.image_label.pixmap() else None
            if current_pixmap_path and os.path.exists(image_path):
                # 简化处理，直接使用索引计算
                current_index = i
                break
        
        # 如果找不到当前图片，则从第一张开始
        if current_index == -1:
            current_index = 0
        else:
            current_index = (current_index + 1) % len(self.image_files)
            
        self.show_image(self.image_files[current_index])

    def previous_image(self):
        """切换到前一张图片"""
        if not self.image_files:
            return
        
        # 查找当前显示的图片文件名
        current_index = 0
        for i, filename in enumerate(self.image_files):
            image_path = os.path.join(self.images_dir, filename)
            current_pixmap_path = self.image_label.pixmap() if self.image_label.pixmap() else None
            if current_pixmap_path and os.path.exists(image_path):
                current_index = i
                break
        
        # 计算前一张图片的索引
        prev_index = (current_index - 1) % len(self.image_files)
        self.show_image(self.image_files[prev_index])